<template>
  <form class="validate-form-container" @submit.prevent="onSubmit">
    <slot name="default"></slot>
    <slot name="submit">
      <button type="submit" class="btn btn-primary">提交</button>
    </slot>
  </form>
</template>

<script lang="ts">
export type TValidateFn = () => boolean;
type Tmitt = Record<"form-item-created", TValidateFn>;
import { defineComponent, onUnmounted } from "vue";
import mitt from "mitt";
export const emitter = mitt<Tmitt>();

export default defineComponent({
  setup(props, { emit }) {
    const funcArr: TValidateFn[] = [];
    const onSubmit = () => {
      const validates = funcArr.map((fn) => fn());
      emit("form-submit", validates);
    };
    const callback = (fn: TValidateFn) => {
      funcArr.push(fn);
    };
    emitter.on("form-item-created", callback);
    onUnmounted(() => {
      emitter.off("form-item-created", callback);
    });
    return {
      onSubmit,
    };
  },
  emits: ["form-submit"],
});
</script>
